/* Copyright 2012 Nathan Begle
    This file is part of pcoursemanager.

    pcoursemanager is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    pcoursemanager is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with pcoursemanager.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;
import java.util.List;

public class Save_Data {
	FileWriter fileWriter;
	File directory = new File("save_data");
	File file = new File(directory, "pcm_save_file.txt");
	BufferedWriter writer;
	
	public Save_Data() {}
	
	public int save_to_file(List<Course> courses)
	{
		if(!check_for_dir())
		{
			directory.mkdirs();
		}

		try {
			if(check_for_file())
			{
				file.delete();
			}
			file.createNewFile();
			fileWriter = new FileWriter(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			writer = new BufferedWriter(fileWriter);
			for(Course i: courses)
			{
				write_file(i.course_crn, i.course_year, i.course_semester);
			}
			writer.close();
			fileWriter.close();
		} catch(Exception e) {
			System.out.println("couldn't write data");
		}
		return 0;
	}
	
	void write_file(long crn, int year, int semester)
	throws Exception
	{		
		String s = String.format("%d&%d&%d", semester, year, crn);
		writer.write(s);
		writer.newLine();
	}
	
	boolean check_for_dir()
	{
		return directory.exists();
	}
	
	boolean check_for_file()
	{
		return file.exists();
	}
}
